<template>
    <div class="risk-item-control-set">
        <div class="risk-control-button">
            <el-card>
                <el-select
                    placeholder="同步类型"
                    size="mini"
                    @change="handleParam(value, 'importType')"
                    class="risk-el-select"
                    style="width:150px;margin-right:10px"
                    v-model="name.syncParam.importType"
                >
                    <el-option v-for="(value, key) in importTypePojo" :value="key" :key="key" :label="key + ' ' + value"></el-option>
                </el-select>
                <el-input
                    placeholder="条目编号"
                    @change="handleParam(name.syncParam.serialNo, 'serialNo')"
                    style="width:100px;margin-right:10px"
                    :style="{ display: name.syncParam.importType === '1' ? '' : 'none' }"
                    size="mini"
                    v-model="name.syncParam.serialNo"
                ></el-input>
                <el-select
                    placeholder="条目类别"
                    @change="handleParam(name.syncParam.entryType, 'entryType')"
                    class="risk-el-select"
                    style="width:150px;margin-right:10px"
                    :style="{ display: name.syncParam.importType === '2' ? '' : 'none' }"
                    size="mini"
                    v-model="name.syncParam.entryType"
                >
                    <el-option
                        v-for="item in hsControlDefines"
                        :key="item.sourceCode"
                        :value="item.sourceCode"
                        :label="item.sourceCode + ' ' + item.sourceName"
                    ></el-option>
                </el-select>
                <el-select
                    placeholder="来源类型"
                    @change="handleParam(name.syncParam.sourceType, 'sourceType')"
                    class="risk-el-select"
                    style="width:150px;margin-right:10px"
                    size="mini"
                    v-model="name.syncParam.sourceType"
                >
                    <el-option value="25" key="25" label="全部"></el-option>
                    <el-option value="2" key="2" label="恒生-主动库"></el-option>
                    <el-option value="5" key="5" label="恒生-被动库"></el-option>
                </el-select>
                <el-switch
                    active-text="执行ETL"
                    inactive-text="跳过ETL"
                    @change="handleParam(name.syncParam.entryETL, 'entryETL')"
                    style="margin-right:10px"
                    size="mini"
                    v-model="name.syncParam.entryETL"
                />
                <el-button icon="el-icon-link" v-authCode.show="B_0087" type="primary" :loading="syncLoading" @click="handleClickSync" size="mini">
                    同步
                </el-button>
                <div style="float:right">
                    <el-input
                        placeholder="条目编号，支持‘,’分割"
                        style="width:250px;margin-right:10px"
                        @change="handleInitEntryCodes"
                        size="mini"
                        v-model="name.initEntryCodes"
                    />
                    <el-button
                        v-authCode.show="B_0087"
                        icon="el-icon-refresh"
                        type="primary"
                        size="mini"
                        :loading="syncLoading"
                        @click="handleInitEntryClick"
                    >
                        初始化
                    </el-button>
                </div>
            </el-card>
        </div>
        <el-tabs v-model="activeKey">
            <el-tab-pane :label="'同步结果'" :name="'current'" :key="'current'">
                <CurrentSyncContent
                    :type="'current'"
                    :outerAmount="outerAmount"
                    :tranParams="{ ...name.syncParam }"
                    :ref="'current'"
                ></CurrentSyncContent>
            </el-tab-pane>
            <el-tab-pane :label="'历史同步结果'" :name="'history'" :key="'history'">
                <HistorySyncContent :type="'history'" :tranParams="name.syncParam" :ref="'history'"></HistorySyncContent>
            </el-tab-pane>
            <!--  <el-tab-pane v-for="item in panes" :label="item.label" :name="item.name" :key="item.name"> -->
        </el-tabs>
        <yh-dialog :visible.sync="verifyDialog" width="700px" :close-on-click-modal="false" drag>
            <template slot="title">
                <span v-html="getSyncItemTitle()" style="color:#fff"></span>
            </template>
            <div>
                <p>同步方式：{{ importTypePojo[name.syncParam.importType] }}</p>
            </div>
            <div v-if="!(paramValue == '0' && name.syncParam.importType != '1')">
                <el-divider></el-divider>
                {{ getSecondTitle() }}：
                <p style="display:inline-block">{{ vertifyInfo.existsEntryCode || '--' }}</p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="verifyDialog = false" :loading="verifyLoading">取 消</el-button>
                <el-button size="mini" type="primary" @click="verifyDialogConfirm" :loading="verifyLoading">确 定</el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import HistorySyncContent from './components/item-sync/history-sync-content.vue';
import CurrentSyncContent from './components/item-sync/current-sync-content.vue';
import { compareEntryCode } from './api';
import { checkPermission } from '@/utils/tools';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'ItemSync',
    components: {
        CurrentSyncContent,
        HistorySyncContent,
    },
})
export default class ItemSync extends Vue {
    private activeKey: string = 'current';
    syncParamApi: any = {};
    panes: any[] = [
        { label: '同步结果', name: 'current' },
        { label: '历史同步结果', name: 'history' },
    ];

    // 同步方式
    importTypePojo = {
        '1': '单个同步',
        '2': '按类别同步',
        '3': '全量同步',
        '4': '增量同步',
    };
    paramValue: string = '0';
    verifyDialog: boolean = false;
    vertifyInfo: any = {};
    isExit: boolean = false;
    private syncLoading: boolean = false;
    private verifyLoading: boolean = false;
    private hsControlDefines: any = [];
    private name: any = {
        syncParam: {
            serialNo: '',
            entryType: '',
            importType: '1',
            entryETL: false,
            sourceType: '2',
        },
        errorMessage: {},
        initEntryCodes: '',
    };
    outerAmount: any = {
        totalAmount: 0,
        successAmount: 0,
        errorAmount: 0,
    };

    mounted() {
        this.isExit = checkPermission('M_206');
        this.$axios.get('/dataEngine/entrytype').then((res: any) => {
            if (res) {
                this.hsControlDefines = res;
            }
        });

        this.handleData();
    }

    private handleParam(value: string, filed: string): void {}

    private handleInitEntryCodes(value: string): void {
        console.log(value, 'handleInitEntryCodes');
    }

    // 初始化
    private handleInitEntryClick(): void {
        if (!this.name.initEntryCodes) {
            this.yh_message_error('请填入条目编号');
            return;
        }
        this.syncLoading = true;
        this.$axios.post('/dataEngine/init/entryCodes', this.name.initEntryCodes.split(',')).then(
            (res: any) => {
                this.yh_message_success('初始化执行成功');
                this.syncLoading = false;
            },
            () => {
                this.syncLoading = false;
            }
        );
    }

    // 同步
    async handleClickSync() {
        let nSyncParam = this.name.syncParam;
        if (nSyncParam.importType === '1') {
            if (!nSyncParam.serialNo) {
                this.yh_message_error('条目编号不可为空');
                return;
            }
        } else if (nSyncParam.importType === '2') {
            if (!nSyncParam.entryType) {
                this.yh_message_error('条目类型不可为空');
                return;
            }
        }
        let syncParam = JSON.parse(JSON.stringify(nSyncParam));

        if (nSyncParam.importType === '1') {
            syncParam.entryType = '';
            syncParam.importType = '';
        } else if (nSyncParam.importType === '2') {
            syncParam.serialNo = '';
            syncParam.importType = '';
        } else if (nSyncParam.importType === '3') {
            syncParam.entryType = '';
            syncParam.serialNo = '';
            syncParam.importType = '1';
        } else if (nSyncParam.importType === '4') {
            syncParam.entryType = '';
            syncParam.serialNo = '';
            syncParam.importType = '0';
        }
        this.syncParamApi = JSON.parse(JSON.stringify(syncParam));

        if (this.isExit) {
            const vertify = await this.verify(syncParam.serialNo, syncParam.entryType);
            if (!vertify) {
                return;
            } else {
                this.verifyDialog = true;
            }
        } else {
            this.syncLoading = true;
            this.verifyDialogConfirm();
        }
    }

    async verify(serialNo, entryType) {
        return new Promise((resolve, reject) => {
            compareEntryCode({
                sourceType: this.name.syncParam.importType,
                noExistsEntryCodes: serialNo ? serialNo.split(',') : [],
                sourceCode: entryType,
            })
                .then((res: any) => {
                    this.vertifyInfo = res;
                    resolve(true);
                })
                .catch(() => {});
        });
    }

    verifyDialogConfirm(isExit?: boolean) {
        this.isExit && (this.verifyLoading = true);
        this.$axios
            .post('dataEngine/syncEntry', this.syncParamApi)
            .then((res: any) => {
                // if (!res.successEntry && !res.errorEntry) {
                //     this.yh_message_error(res.errorMsg);
                //     this.syncLoading = false;
                //     return;
                // }
                this.outerAmount.totalAmount = res.totalAmount || 0;
                this.outerAmount.successAmount = res.successAmount || 0;
                this.outerAmount.errorAmount = res.errorAmount || 0;

                // if (!res.batchId && res.batchId !== 0) {
                this.beforeDestory();
                this.handleData(res.batchId);
                // }
            })
            .finally(() => {
                if (this.isExit) {
                    this.verifyLoading = false;
                    this.verifyDialog = false;
                } else {
                    this.syncLoading = false;
                }
            });
    }

    async handleData(batchId?: any) {
        // 将batchId传递给子组件
        (this.$refs['current'] as any).handleClickSync('0', false, '1', 'userAction', batchId);
        (this.$refs['current'] as any).handleClickSync('1', false, '1', 'userAction', batchId);
        this.setIntervalCurrent = setInterval(() => {
            (this.$refs['current'] as any).handleClickSync('1', true, '1', 'autoRefresh');
        }, 60 * 1000);
        (this.$refs['history'] as any).handleClickSync('1');
    }

    setIntervalCurrent = null;

    beforeDestory() {
        console.log('beforeDestory-------------');
        if (this.setIntervalCurrent) {
            clearInterval(this.setIntervalCurrent);
            this.setIntervalCurrent = null;
        }
    }

    getSyncItemTitle() {
        const importType = this.name.syncParam.importType;
        const paramValue = this.vertifyInfo.lmtType;
        this.paramValue = paramValue;
        let retValue = '';
        if (importType === '1' || paramValue == '0') {
            return `<span>确定进行条目同步吗？</span>`;
        } else {
            if (paramValue == '1') {
                retValue = '已自动过滤未处于"白名单"中的条目';
            } else if (paramValue == '2') {
                retValue = '已自动过滤"黑名单"中条目';
            }
            return `<span>确定进行条目同步吗？</span>
            <span style="font-size:12px">(${retValue})</span>`;
        }
    }

    getSecondTitle() {
        const importType = this.name.syncParam.importType;
        const paramValue = this.vertifyInfo.lmtType;
        let retValue = '';
        if (importType == '1') {
            retValue = '同步条目';
        } else {
            if (paramValue == '1') {
                retValue = '未处于"白名单"中的条目';
            } else if (paramValue == '2') {
                retValue = '"黑名单"中条目';
            }
        }
        return retValue;
    }
}
</script>
<style lang="scss" scoped>
.risk-item-control-set {
    min-width: 1200px;
}
/deep/ .el-tabs .el-tabs__nav .el-tabs__item {
    border: 1px solid #cacaca !important;
    margin: 5px;
    height: 100%;
}
/deep/ .el-tab-pane {
    color: #000;
}
</style>
